import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { ReviewPageService } from './review-page.service';
import { FlowInfoComponent } from '../../modal/flow-info/flow-info.component';
import { ReviewBackComponent } from '../../modal/review-back/review-back.component';
import { ViewDetailComponent } from '../../modal/view-detail/view-detail.component';
import * as _ from "lodash";
import { PaginationModel } from 'app/widgets/pagination';
import { Util } from '../../../../../common/util';
import { DataService } from 'app/services/data.service';
import { TablePageComponent } from '../../modal/table/table-page/table-page.component';

@Component({
  selector: 'app-review-page',
  templateUrl: './review-page.component.html',
  styleUrls: ['./review-page.component.scss'],
  providers: [ReviewPageService]
})
export class ReviewPageComponent implements OnInit {

  //条目复核列表
  @ViewChild("reviewTablePage", { read: ViewContainerRef })
  reviewTablePage: ViewContainerRef;
  tablePageComponent: ComponentRef<TablePageComponent>;
  // 查看流程信息modal
  @ViewChild("flowInfo", { read: ViewContainerRef })
  flowInfo: ViewContainerRef;
  flowInfoComponent: ComponentRef<FlowInfoComponent>;

  // 条目复核通过modal
  @ViewChild("review", { read: ViewContainerRef })
  review: ViewContainerRef;
  reviewComponent: ComponentRef<ReviewBackComponent>;

  // 返回modal
  // @ViewChild("back", { read: ViewContainerRef })
  // back: ViewContainerRef;
  // backComponent: ComponentRef<ReviewBackComponent>;

  // 查看明细modal
  @ViewChild("detail", { read: ViewContainerRef })
  detail: ViewContainerRef;
  viewDetailComponent: ComponentRef<ViewDetailComponent>;

  public fundGroupChosen: any;
  //列表克隆数据
  public cloneList: any;
  // lodash
  public _: any = _;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];
  public isCheckedAll: any;

  // 明细模式列表数据
  public listData: any;

  // 批次模式列表数据
  public batchListData: any = [];

  // 适用基金组数据
  public fundGroup: any = [];

  // 字典值
  public dictionaryList: any;

  // 查看已勾选项目
  public checkedList: any = [];

  //明细模式分页配置
  public listPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 0,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  //批次模式分页配置
  public batchListPageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 50,
    totalPages: 0,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };



  //查询分页列表post数据
  public getListBody: any = {
    pageIndex: 1,
    pageSize: 50,
    sOprDateStart: '',
    sOprDateEnd: '',
    nBatchNoStart: '',
    nBatchNoEnd: '',
    sFileName: '',
    sOpr: '',
    sFundType: '',
    sFundGroupds: ''
  };
  public sFundType: any = [];
  public sFundGroupds: any = [];
  // 批次模式分页列表post数据
  public batchListBody = {
    pageIndex: 1,
    pageSize: 50,
    sOprDateStart: '',
    sOprDateEnd: '',
    nBatchNoStart: '',
    nBatchNoEnd: ''
  }
  // 查看已勾选body
  public getbody = {
    nIds: '',
    pageIndex: this.getListBody.pageIndex,
    pageSize: this.getListBody.pageSize
  }
  constructor(
    public reviewService: ReviewPageService,
    public resolver: ComponentFactoryResolver,
    public dataService: DataService
  ) { }

  ngOnInit() {
    this.dataService.nQDIIReviewBackEmitter = new EventEmitter();
    this.dataService.nQDIIReviewBackEmitter.subscribe((value: any) => {
      window['$']('#modal2').modal('hide');
      window['$']('#modal4').modal('hide');
      this.loadList();
      this.loadBatchList();
    });
    let that = this;
    // 字典值
    this.dictionaryList = JSON.parse(localStorage.getItem("dictionaryList"));
    // 多选下拉框
    window['$'](".select2").select2();
    this.fundGroupBaseList();
    this.loadList();
    Util.loadSelect(this.dictionaryList.RISK_ACCOUNT_TYPE, 'NqdiiReviewFundType', 140)
    // setTimeout(() => {
    //   this.fundGroupsSelect2();
    // }, 500)
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        // let SessionMenuData = sessionStorage.getItem('menu');
        // this.menuData = JSON.parse(SessionMenuData)
        // this.menuResourceSet = [];
        // _.forEach(this.menuData, (item, index) => {
        //   if (item.sName == '风控管理') {
        //     _.forEach(item.children, (it, idx) => {
        //       if (it.sName == '非QDII条目管理') {
        //         _.forEach(it.children, (ite, i) => {
        //           if (ite.sName == '条目复核') {
        //             that.menuResourceSet = ite.resourceSet
        //             sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
        //           }
        //         })
        //       }
        //     })
        //   }
        // })
        this.menuResourceSet = [];
        this.menuResourceSet = Util.getAuthority('风控管理', '非QDII条目管理', '条目复核');
        sessionStorage.setItem('btn-NQDII', this.menuResourceSet);
      }
    })
    this.menuResourceSet = [];
    this.menuResourceSet = Util.getAuthority('风控管理', '非QDII条目管理', '条目复核');
    sessionStorage.setItem('btn-NQDII', this.menuResourceSet);

  }

  showReview(index) {
    let that = this;
    // 明细模式的已勾选
    let checkProduct = [];
    // 批次模式的已勾选
    let batchCheckProduct = [];
    // 已勾选的批次号
    let batchNo = [];
    _.forEach(this.listData, item => {
      if (item.isChecked) {
        batchNo.push(item.nBatchNo);
        checkProduct.push(item);
      }
    });
    // 批次号去重
    let array = Array.from(new Set(batchNo));
    if (array.length > 1) {

      window["swal"]("提示", "请不要跨批次号操作", "warning");
    }
    else if (array.length == 0) {
      window["swal"]("提示", "请选择操作条目！", "warning");
    }
    else {
      let lockbody = {
        nIdList: []
      }
      lockbody.nIdList.push(checkProduct[0].nId)
      console.log(lockbody)
      this.reviewService.lockState(lockbody).subscribe((data) => {
        console.log(data);
        if (data == true) {
          if (this.reviewComponent && this.reviewComponent.instance) {
            this.reviewComponent.destroy();
          }
          // 动态创建组件的实例
          const reviewBackComponent = this.resolver.resolveComponentFactory(ReviewBackComponent);
          this.reviewComponent = this.review.createComponent(reviewBackComponent);
          this.reviewComponent.instance.showTip = index;
          this.reviewComponent.instance.receivedItem = checkProduct;
          window['$']('#modal2').modal('show');
        }
        else {
          window["swal"]("提示", "加锁失败", "warning");
        }
      })

    }

  }

  // 显示modal
  showModal(index) {
    let that = this;
    // 明细模式的已勾选
    let checkProduct = [];
    // 批次模式的已勾选
    let batchCheckProduct = [];
    // 已勾选的批次号
    let batchNo = [];
    switch (index) {
      case '1':
        _.forEach(this.listData, item => {
          if (item.isChecked) {
            checkProduct.push(item);
          }
        });
        if (checkProduct.length == 1) {
          if (this.flowInfoComponent && this.flowInfoComponent.instance) {
            this.flowInfoComponent.destroy();
          }
          // 动态创建组件的实例
          const flowInfoComponent = this.resolver.resolveComponentFactory(FlowInfoComponent);
          this.flowInfoComponent = this.flowInfo.createComponent(flowInfoComponent);
          this.flowInfoComponent.instance.item = checkProduct[0];
          window['$']('#modal1').modal('show');

        } else {
          window["swal"]("提示", "请选择一条记录！", "warning");
        }
        break;
      case '4':
        _.forEach(this.batchListData, item => {
          if (item.isChecked) {
            batchCheckProduct.push(item);
          }
        });
        if (batchCheckProduct.length == 1) {
          if (this.viewDetailComponent && this.viewDetailComponent.instance) {
            this.viewDetailComponent.destroy();
          }
          // 动态创建组件的实例
          const viewDetailComponent = this.resolver.resolveComponentFactory(ViewDetailComponent);
          this.viewDetailComponent = this.detail.createComponent(viewDetailComponent);
          this.viewDetailComponent.instance.receivedItem = batchCheckProduct[0];
          this.viewDetailComponent.instance.viewDetailType = '2';
          // 传入菜单按钮权限
          this.viewDetailComponent.instance.menuResource = this.menuResourceSet;
          window['$']('#modal4').modal('show');
        } else {
          window["swal"]("提示", "请选择一条记录！", "warning");
        }

        break;
    }
  }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
      _.forEach(this.batchListData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
      _.forEach(this.batchListData, item => {
        item.isChecked = false;
      });
    }
    this.ctrlCheckAll()
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    let thisPageChecked = [];
    _.forEach(this.listData, item => {
      let isChongfu = false;
      if (item.isChecked == true) {
        thisPageChecked.push(item);
        _.forEach(this.checkedList, it => {
          if (it.nId == item.nId) {
            isChongfu = true;
          }
        })
        if (!isChongfu) {
          this.checkedList.push(item);
        }
      } else {
        this.checkedList = _.filter(this.checkedList, function (it: any) {
          return it.nId != item.nId;
        });

      }

    })

    if (thisPageChecked.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 明细模式列表
  loadList(pageNum?, pageSize?, mode?) {
    let that = this;
    let pageIndex;
    if (mode == 'clear') {
      // 清空搜索条件
      Util.clearSearchConditions(this.getListBody, [pageSize, pageIndex])

    }
    this.getListBody.sFundType = this.sFundType.join(',');
    this.getListBody.sFundGroupds = this.sFundGroupds.join(',');
    this.isCheckedAll = false;
    this.getListBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    this.getListBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.reviewService.list(this.getListBody).subscribe(data => {
      if (data) {
        this.listData = data.list;
        this.cloneList = _.cloneDeep(data.list);
        this.controlDom();
        this.showTablePage(this.listData)
        this.listPageInfo.currentPageNum = data.pageNum;
        this.listPageInfo.totalPages = data.pages;
        this.listPageInfo.total = data.total;
        this.listPageInfo.startRow = data.startRow;
        this.listPageInfo.endRow = data.endRow;
        if (that.checkedList.length > 0) {
          _.forEach(that.listData, item => {
            _.forEach(that.checkedList, it => {
              if (it.nId == item.nId) {
                item.isChecked = it.isChecked
              }
            })
          })
          that.ctrlCheckAll();
        }
      }
    });
  }
  // 批次模式列表
  loadBatchList(pageNum?, pageSize?, mode?) {
    let pageIndex;
    if (mode == 'clear') {
      // 清空搜索条件
      Util.clearSearchConditions(this.batchListBody, [pageSize, pageIndex])
    }
    let that = this;
    this.isCheckedAll = false;
    this.batchListBody.pageIndex = pageNum ? pageNum : this.batchListPageInfo.currentPageNum;
    this.batchListBody.pageSize = pageSize ? pageSize : this.batchListPageInfo.pageSize;
    this.reviewService.batchList(this.batchListBody).subscribe((data) => {
      if (data) {
        console.log(data);
        this.batchListData = data.list;
        this.batchListPageInfo.currentPageNum = data.pageNum;
        this.batchListPageInfo.totalPages = data.pages;
        this.batchListPageInfo.total = data.total;
        this.batchListPageInfo.startRow = data.startRow;
        this.batchListPageInfo.endRow = data.endRow;
      }
    })
  }
  // 个数分页
  pageSizeChange(pageSize: number, flag: number) {
    if (flag == 1) {
      if (pageSize !== this.listPageInfo.pageSize) {
        this.listPageInfo.pageSize = pageSize;
        this.loadList();
      }
    }
    if (flag == 2) {
      if (pageSize !== this.batchListPageInfo.pageSize) {
        this.batchListPageInfo.pageSize = pageSize;
        this.loadBatchList();
      }
    }
  }
  // 页码分页
  PageNavigation(currentPageNum: number, flag: number) {
    if (flag == 1) {
      this.listPageInfo.currentPageNum = currentPageNum;
      this.loadList(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
    }
    if (flag == 2) {
      this.batchListPageInfo.currentPageNum = currentPageNum;
      this.loadBatchList(this.batchListPageInfo.currentPageNum, this.batchListPageInfo.pageSize);
    }
  }

  // 获取适用基金组
  fundGroupBaseList() {
    let getbody = {
      sType: 0,//非QDII传0
    }
    this.reviewService.fundGroupList(getbody).subscribe((data) => {
      this.fundGroup = data
      let that = this;
      var html = '';
      for (var i = 0; i < this.fundGroup.length; i++) {
        html += "<option value='" + this.fundGroup[i].nFgId + "'>" + this.fundGroup[i].sFgName + "</option>";
      }
      window['$']("#NqdiiReviewFundGroupds").html(html);
      window['$']('#NqdiiReviewFundGroupds').selectpicker({
        size: "8",
        actionsBox: "true",
        title: "请选择",
        selectAllText: "全选",
        deselectAllText: "取消全选",
        width: 140
      });
    })
  }
  //初始化适用基金组多选框
  // fundGroupsSelect2() {
  //   let that = this;
  //   var html = '';
  //   for (var i = 0; i < this.fundGroup.length; i++) {
  //     html += "<option value='" + this.fundGroup[i].nFgId + "'>" + this.fundGroup[i].sFgName + "</option>";
  //   }
  //   window['$']("#NqdiiReviewFundGroupds").html(html);
  //   window['$']('#NqdiiReviewFundGroupds').selectpicker({
  //     size: "8",
  //     actionsBox: "true",
  //     title: "请选择",
  //     selectAllText: "全选",
  //     deselectAllText: "取消全选",
  //     width: 150
  //   });
  // }
  // 查看已勾选
  viewChecked() {
    // console.log(this.checkedList);
    let nIds = [];

    _.forEach(this.listData, item => {
      // console.log(item);
      if (item.isChecked) {
        nIds.push(item.nId)
      }

    })
    if (nIds.length > 0) {
      this.getbody.nIds = nIds.join(',');
      console.log(this.getbody)
      this.reviewService.viewChecked(this.getbody).subscribe((data) => {
        if (data) {
          console.log(data)
          this.listData = data.list;
          this.cloneList = _.cloneDeep(data.list);
          this.controlDom();
          this.showTablePage(this.listData)
          this.listPageInfo.currentPageNum = data.pageNum;
          this.listPageInfo.totalPages = data.pages;
          this.listPageInfo.total = data.total;
          this.listPageInfo.startRow = data.startRow;
          this.listPageInfo.endRow = data.endRow;
          this.checkedList = [];
          this.isCheckedAll = false
          this.checkedAll();
        }
      })
    }
    else {
      window["swal"]("提示", "未勾选任何条目", "warning");
    }
  }

  //搜索查询
  searchQuery(list) {
    let that = this;
    if (Util.dateOrder(list.sOprDateStart, list.sOprDateEnd)) {
      if (list.nBatchNoEnd != '' && list.nBatchNoStart != '') {
        if (parseInt(list.nBatchNoEnd) > parseInt(list.nBatchNoStart)) {
          that.loadBatchList();
          that.loadList(1);
        } else {
          window['swal']("提示", "起始批次 须小于 结束批次", "warning");
        }
      } else {
        that.loadBatchList();
        that.loadList(1);
      }
    } else {
      window['swal']("提示", "发行日期 须早于 到期日期", "warning");
    }
  }

  //根据编号是否相同操控dom
  controlDom() {
    let that = this;
    if (this.listData != undefined) {
      for (let i = 0; i < this.listData.length - 1; i++) {
        if (that.listData[i].nNjId == that.listData[i + 1].nNjId) {
          // window['$']('#routeCheck' + i).remove();
          _.forIn(that.listData[i], (item1, key1) => {
            let index1 = i + 1;
            let index2 = i + 2;
            let id1 = "#review-table tbody tr:nth-child(" + index1 + ") td div[name=" + key1 + "]";
            let id2 = "#review-table tbody tr:nth-child(" + index2 + ") td div[name=" + key1 + "]";
            if (item1 == that.listData[i + 1][key1]) {
              // window['$'](id1).removeClass('font-color');
              // window['$'](id2).removeClass('font-color');
            } else {
              // window['$'](id1).removeClass('font-color');
              that.cloneList[i + 1][key1] = 'red';
            }
          })
        }
      }
    }
  }
  // 修改标蓝(i为下标,value为修改后的值,name为字段名)
  inputChange(i: any, value: any, name: any, itemCode?) {
    let that = this

    // 定位tr
    let index = i + 1;
    // 定位输入框和选择框
    let id = "#review-table tbody tr:nth-child(" + index + ") td div[id=" + name + "]";
    // let id2 = "#input-table tbody tr:nth-child(" + index + ") td select[name=" + name + "]";
    // 获取当前修改对象
    let item = this.cloneList[i];
    // 循环对象
    for (let key in item) {
      // 判断字段名是否相等
      if (key == name) {
        // 判断原值是否为null(后端空值返回null,前端空值为'',实际都为空,相等)
        if (item[key] == null) {
          if (value == '') {


            window['$'](id).removeClass('triangle-topleft');
          } else {


            window['$'](id).addClass('triangle-topleft');
          }
        } else {
          // 判断原值不为null,直接对比
          if (item[key] == value) {

            window['$'](id).removeClass('triangle-topleft');
          } else {

            window['$'](id).addClass('triangle-topleft');
          }
        }
      }
    }
  }
  //条目复核列表
  showTablePage(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.tablePageComponent && this.tablePageComponent.instance) {
      this.tablePageComponent.destroy();
    }

    // 动态创建组件的实例
    const tablePageComponent = this.resolver.resolveComponentFactory(TablePageComponent);
    this.tablePageComponent = this.reviewTablePage.createComponent(tablePageComponent);
    this.tablePageComponent.instance.listData = item;
    this.tablePageComponent.instance.listType = '7';
    this.tablePageComponent.instance.setColor = this.cloneList;
  }
}
